﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Syndication;

using DesdemonaDespairLib;
using DesdemonaDespairApp.Data;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using System.Diagnostics;
using Windows.Storage;
using Windows.Storage.Streams;

// The Split Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234234

namespace DesdemonaDespairApp
{
    /// <summary>
    /// A page that displays a group title, a list of items within the group, and details for the
    /// currently selected item.
    /// </summary>
    public sealed partial class SplitPage : DesdemonaDespairApp.Common.LayoutAwarePage
    {
        public SplitPage()
        {
            this.InitializeComponent();

            RegisterForShare();

            RegisterBackgroundTask();

            SettingsPane.GetForCurrentView().CommandsRequested += onCommandsRequested;
        }

        void onCommandsRequested( SettingsPane settingsPane, SettingsPaneCommandsRequestedEventArgs eventArgs )
        {
            UICommandInvokedHandler handler = new UICommandInvokedHandler( onSettingsCommand );

            SettingsCommand privacyStatementCommand = new SettingsCommand( "privacyStatement", "Privacy Statement", handler );
            eventArgs.Request.ApplicationCommands.Add( privacyStatementCommand );

            //SettingsCommand generalCommand = new SettingsCommand( "generalSettings", "General", handler );
            //eventArgs.Request.ApplicationCommands.Add( generalCommand );

            //SettingsCommand helpCommand = new SettingsCommand( "helpPage", "Help", handler );
            //eventArgs.Request.ApplicationCommands.Add( helpCommand );
        }

        async void onSettingsCommand( IUICommand command )
        {
            SettingsCommand settingsCommand = (SettingsCommand)command;

            if( (string)settingsCommand.Id == "privacyStatement" )
            {
                Uri privacyStatementUri = new Uri( privacyStatementUrl );
                await Windows.System.Launcher.LaunchUriAsync( privacyStatementUri );
            }

            Debug.WriteLine(
                "You selected the " +
                settingsCommand.Label +
                " settings command which originated from the " +
                SettingsPane.Edge.ToString() );
        }



        #region Page state management

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState( Object navigationParameter, Dictionary<String, Object> pageState )
        {
            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            //var group = SampleDataSource.GetGroup((String)navigationParameter);
            //this.DefaultViewModel["Group"] = group;
            //this.DefaultViewModel["Items"] = group.Items;

            var items = await Utilities.GetDesdemonaBlogItems();
            this.itemsViewSource2.Source = items;

            if( pageState == null )
            {
                this.itemListView.SelectedItem = null;
                // When this is a new page, select the first item automatically unless logical page
                // navigation is being used (see the logical page navigation #region below.)
                //if (!this.UsingLogicalPageNavigation() && this.itemsViewSource2.View != null)
                {
                    this.itemsViewSource2.View.MoveCurrentToFirst();
                }
            }
            else
            {
                // Restore the previously saved state associated with this page
                if( pageState.ContainsKey( "SelectedItem" ) && this.itemsViewSource2.View != null )
                {
                    var selectedItem = SampleDataSource.GetItem( (String)pageState["SelectedItem"] );
                    this.itemsViewSource2.View.MoveCurrentTo( selectedItem );
                }
            }
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState( Dictionary<String, Object> pageState )
        {
            if( this.itemsViewSource2.View != null )
            {
                var selectedItem = (DesdemonaSyndicationItem)this.itemsViewSource2.View.CurrentItem;
                if( selectedItem != null ) pageState["SelectedItem"] = selectedItem.id; //selectedItem.UniqueId;
            }
        }

        #endregion

        #region Logical page navigation

        // Visual state management typically reflects the four application view states directly
        // (full screen landscape and portrait plus snapped and filled views.)  The split page is
        // designed so that the snapped and portrait view states each have two distinct sub-states:
        // either the item list or the details are displayed, but not both at the same time.
        //
        // This is all implemented with a single physical page that can represent two logical
        // pages.  The code below achieves this goal without making the user aware of the
        // distinction.

        /// <summary>
        /// Invoked to determine whether the page should act as one logical page or two.
        /// </summary>
        /// <param name="viewState">The view state for which the question is being posed, or null
        /// for the current view state.  This parameter is optional with null as the default
        /// value.</param>
        /// <returns>True when the view state in question is portrait or snapped, false
        /// otherwise.</returns>
        //private bool UsingLogicalPageNavigation( ApplicationViewState? viewState = null )
        //{
        //    if( viewState == null ) viewState = ApplicationView.Value;
        //    return viewState == ApplicationViewState.FullScreenPortrait ||
        //        viewState == ApplicationViewState.Snapped;
        //}

        /// <summary>
        /// Invoked when an item within the list is selected.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is Snapped)
        /// displaying the selected item.</param>
        /// <param name="e">Event data that describes how the selection was changed.</param>
        void ItemListView_SelectionChanged( object sender, SelectionChangedEventArgs e )
        {
            if( e.AddedItems.Count > 0 )
            {
                DesdemonaSyndicationItem item = e.AddedItems[0] as DesdemonaSyndicationItem;

                //ApplicationViewState currentState = Windows.UI.ViewManagement.ApplicationView.Value;
                string currentState = DetermineVisualState();
                if( currentState == "Snapped" )
                {
                    LaunchBrowserWithSelectedItem();
                }
                else
                {
                    try
                    {
                        this.webView.NavigateToString( item.content );
                    }
                    catch( Exception ex )
                    {
                        Debug.WriteLine( ex.ToString() );
                    }
                }
            }
        }

        /// <summary>
        /// Invoked when the page's back button is pressed.
        /// </summary>
        /// <param name="sender">The back button instance.</param>
        /// <param name="e">Event data that describes how the back button was clicked.</param>
        protected override void GoBack( object sender, RoutedEventArgs e )
        {
            base.GoBack( sender, e );
        }

        /// <summary>
        /// Invoked to determine the name of the visual state that corresponds to an application
        /// view state.
        /// </summary>
        /// <param name="viewState">The view state for which the question is being posed.</param>
        /// <returns>The name of the desired visual state.  This is the same as the name of the
        /// view state except when there is a selected item in portrait and snapped views where
        /// this additional logical page is represented by adding a suffix of _Detail.</returns>
        //protected override string DetermineVisualState(ApplicationViewState viewState)
        //{
        //    // Update the back button's enabled state when the view state changes
        //    var logicalPageBack = this.UsingLogicalPageNavigation(viewState) && this.itemListView.SelectedItem != null;
        //    var physicalPageBack = this.Frame != null && this.Frame.CanGoBack;
        //    this.DefaultViewModel["CanGoBack"] = logicalPageBack || physicalPageBack;

        //    // Determine visual states for landscape layouts based not on the view state, but
        //    // on the width of the window.  This page has one layout that is appropriate for
        //    // 1366 virtual pixels or wider, and another for narrower displays or when a snapped
        //    // application reduces the horizontal space available to less than 1366.
        //    if (viewState == ApplicationViewState.Filled ||
        //        viewState == ApplicationViewState.FullScreenLandscape)
        //    {
        //        var windowWidth = Window.Current.Bounds.Width;
        //        if (windowWidth >= 1366) return "FullScreenLandscapeOrWide";
        //        return "FilledOrNarrow";
        //    }

        //    // When in portrait or snapped start with the default visual state name, then add a
        //    // suffix when viewing details instead of the list
        //    var defaultStateName = base.DetermineVisualState();
        //    return logicalPageBack ? defaultStateName + "_Detail" : defaultStateName;
        //}

        #endregion

        private void browserButton_Click( object sender, RoutedEventArgs e )
        {
            LaunchBrowserWithSelectedItem();
        }

        private async void LaunchBrowserWithSelectedItem()
        {
            if( this.itemListView.SelectedItem != null )
            {
                DesdemonaSyndicationItem selectedItem = this.itemListView.SelectedItem as DesdemonaSyndicationItem;
                await Windows.System.Launcher.LaunchUriAsync( selectedItem.url );
            }
        }

        private async void refreshButton_Click( object sender, RoutedEventArgs e )
        {
            var items = await Utilities.GetDesdemonaBlogItems();
            this.itemsViewSource2.Source = items;
        }

        private void RegisterForShare()
        {
            DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
            dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,
                DataRequestedEventArgs>( this.ShareLinkHandler );
        }

        private void ShareLinkHandler( DataTransferManager sender, DataRequestedEventArgs e )
        {
            if( this.itemListView.SelectedItem != null )
            {
                DesdemonaSyndicationItem selectedItem = this.itemListView.SelectedItem as DesdemonaSyndicationItem;

                DataRequest request = e.Request;
                request.Data.Properties.Title = "Share link from Desdemona Despair";
                request.Data.Properties.Description = selectedItem.Title;
                request.Data.SetWebLink( selectedItem.url );
            }
        }

        private async void RegisterBackgroundTask()
        {
            var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
            if( backgroundAccessStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity ||
                backgroundAccessStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity )
            {
                foreach( var task in BackgroundTaskRegistration.AllTasks )
                {
                    if( task.Value.Name == taskName )
                    {
                        task.Value.Unregister( true );
                    }
                }

                BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
                taskBuilder.Name = taskName;
                taskBuilder.TaskEntryPoint = taskEntryPoint;
                taskBuilder.SetTrigger( new TimeTrigger( updatePeriodInMinutes, false ) );
                var registration = taskBuilder.Register();
            }
        }

        private const string taskName = "BlogFeedBackgroundTask";
        private const string taskEntryPoint = "BackgroundTasks.DesdemonaFeedBackgroundTask";
        private const string privacyStatementUrl = "http://www.leftopia.com/commerce/PrivacyStatement.html";
        private const uint updatePeriodInMinutes = 120; // The minimum value is 15.
    }
}
